<script setup>
import { Search } from '@element-plus/icons-vue'
import {onMounted, ref, computed} from 'vue'
import axios from "axios";
import {ElMessage} from "element-plus";
import {router} from "@/router/index.js";

const showAdvancedDialog = ref(false)

// 状态映射表
const statusMap = {
  1: '待付款',
  2: '待发货',
  3: '已发货',
  4: '已完成',
  5: '已关闭'
}

// 计算属性：统计各状态订单数量
const statusCounts = ref({
    '全部': 0,
    '待付款': 0,
    '待发货': 0,
    '已发货': 0,
    '已完成': 0,
    '已关闭': 0

})

const fetchStatusCounts = () => {
  axios.get('/order/getStatusCounts').then(res => {
    statusCounts.value = {
      '全部': res.data.total || 0,
      '待付款': res.data.waitPay || 0,
      '待发货': res.data.waitShip || 0,
      '已发货': res.data.shipped || 0,
      '已完成': res.data.completed || 0,
      '已关闭': res.data.closed || 0
    }
  })
}

const closeOrderDialogVisible = ref(false)
const currentOrder = ref(null)
const operationDescription = ref('')
// 点击状态卡片事件
const handleStatusClick = (status) => {
  if(status !== 'full') {
    axios.get(`/order/getOrderByStatus/${status}`).then(res => {
      tableData.value = res.data.map(item => ({
        ...item,
        orderStatus: typeof item.orderStatus === 'number'
            ? statusMap[item.orderStatus]
            : item.orderStatus
      }))
      fetchStatusCounts() // 调用API获取最新状态统计数据
    })
  } else {
    initData().then(() => fetchStatusCounts()) // 初始化数据并获取状态统计数据
  }
}



// 重置高级筛选表单
const resetAdvancedForm = () => {
  advancedForm.value = {
    startDate: '',
    endDate: '',
    orderNumber: '',
    userAccount: '',
    orderStatus: '',
    orderSource: ''
  }
}

// 应用高级筛选

const applyAdvancedFilter = () => {
  const params = {
    ...advancedForm.value,
    orderStatus: advancedForm.value.orderStatus
        ? (typeof advancedForm.value.orderStatus === 'string'
            ? Number(Object.keys(statusMap).find(key => statusMap[key] === advancedForm.value.orderStatus))
            : advancedForm.value.orderStatus)
        : ''
  }

  axios.post('/order/selectOrders', params).then(res => {
    tableData.value = res.data.map(item => ({
      ...item,
      orderStatus: typeof item.orderStatus === 'number'
          ? statusMap[item.orderStatus]
          : item.orderStatus
    }))
    if (res.data.total !== undefined) {
      total.value = res.data.total
    } else {
      total.value = res.data.length || 0
    }

    currentPage.value = 1
    showAdvancedDialog.value = false
  })
}

const handleDateChange = (dates) => {
  if (dates && dates.length === 2) {
    advancedForm.value.startDate = dates[0]
    advancedForm.value.endDate = dates[1]
  } else {
    advancedForm.value.startDate = ''
    advancedForm.value.endDate = ''
  }
}

// 查询表单
const queryForm = ref({
  orderNo: '',
  userAccount: '',
  orderStatus: ''
})

const advancedForm = ref({
  startDate: '', // 新增：开始日期
  endDate: '',   // 新增：结束日期
  orderNumber: '',
  userAccount: '',
  orderStatus: '',
  orderSource: ''
})

const showAdvanced = ref(false)

// 表格数据
const tableData = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

const initData = () => {
  axios.get(`/order/getAllOrders/${pageSize.value}/${currentPage.value}`).then(res => {
    tableData.value = res.data.data.map(item => ({
      ...item,
      // 如果orderStatus是数字，转换为对应的文本
      orderStatus: typeof item.orderStatus === 'number'
          ? statusMap[item.orderStatus]
          : item.orderStatus
    }));
    total.value = res.data.total;
  })
}

const getOrderStatus = () => {
  axios.get(`/order/getOrderStatus`).then(res => {
    // 生成 {value: 数字, label: 文字} 格式的选项
    statusOption.value = res.data.map(status => ({
      value: status,
      label: statusMap[status] || status.toString()
    }))
  })
}

const getOrderSource = ()=>{
  axios.get(`/order/getOrderSource`).then(res => {
    sourceOption.value = res.data
  })
}

// 方法
const resetQuery = () => {
  queryForm.value = {
    orderNo: '',
    userAccount: '',
    orderStatus: ''
  }
  advancedForm.value = {
    dateRange: [],
    source: '',
    payment: ''
  }
}

const handleQuery = () => {
  // 转换状态文本为数字
  const params = {
    ...queryForm.value,
    orderStatus: queryForm.value.orderStatus
        ? (typeof queryForm.value.orderStatus === 'string'
            ? Number(Object.keys(statusMap).find(key => statusMap[key] === queryForm.value.orderStatus))
            : queryForm.value.orderStatus)
        : ''
  }

  axios.post('/order/selectOrders', params).then(res => {
    tableData.value = res.data.map(item => ({
      ...item,
      orderStatus: typeof item.orderStatus === 'number'
          ? statusMap[item.orderStatus]  // 将数字状态转为文本显示
          : item.orderStatus
    }))
    total.value = res.data.total || res.data.length || 0
    currentPage.value = 1
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchOrders()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchOrders()
}

const fetchOrders = () => {
  // 实际项目中这里应该调用API
  console.log('Fetching orders with params:', {
    ...queryForm.value,
    ...advancedForm.value,
    page: currentPage.value,
    size: pageSize.value
  })
}

const getStatusType = (status) => {
  // 如果status是数字，先转换为文本
  const statusText = typeof status === 'number' ? statusMap[status] : status

  const typeMap = {
    '待付款': 'warning',
    '待发货': '',
    '已发货': 'info',
    '已完成': 'success',
    '已关闭': 'danger'
  }
  return typeMap[statusText] || ''
}

const selectedOrders = ref([]) // 用于存储选择的订单

const printOrder = () => {
  console.log('合并订单')
}

const printPreview = () => {
  console.log('打印预览单')
}

const exportOrder = () => {
  axios.post('/order/download', selectedOrders.value, {
    responseType: 'blob' // 关键：告诉 Axios 接收的是二进制文件
  }).then(res => {
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.setAttribute('download', '订单数据.xlsx'); // 设置下载文件名
    document.body.appendChild(link);
    link.click();
    link.remove();
  }).catch(err => {
    console.error("下载失败", err);
    ElMessage.error("下载失败");
  });
}
const handleSelectionChange = (selection) => {
  selectedOrders.value = selection.map(row => row.id);
}
const id =ref(-1);
const status = ref(null);
const viewOrder = (row) => {
   id.value = row.id;
   status.value = row.status;
 router.push(`orderDetail?id=${id.value} `);
}

const closeOrder = (row) => {
  currentOrder.value = row
  operationDescription.value = ''
  closeOrderDialogVisible.value = true
}
const confirmCloseOrder = () => {
  axios.delete(`/order/deleteOrder/${currentOrder.value.id}/${operationDescription.value}`).then(res => {})
}

const statusOption = ref([])

const sourceOption = ref([])

const mergeOrderDialogVisible = ref(false)
const mainOrder = ref(null)
const subOrders = ref([])
const mergeOrderOptions = ref([])

const openMergeOrderDialog = () => {
  if (selectedOrders.value.length < 2) {
    ElMessage.warning('请至少选择2个订单进行合并')
    return
  }

  // 获取选中订单的详细信息
  mergeOrderOptions.value = tableData.value.filter(item =>
      selectedOrders.value.includes(item.id))

  mainOrder.value = null
  subOrders.value = []
  mergeOrderDialogVisible.value = true
}

const confirmMergeOrder = () => {
  if (!mainOrder.value) {
    ElMessage.warning('请选择主订单')
    return
  }

  if (subOrders.value.length === 0) {
    ElMessage.warning('请选择至少一个从订单')
    return
  }

  const params = {
    mainOrderId: mainOrder.value,
    subOrderIds: subOrders.value,
  }

  axios.post('/order/mergeOrders', params).then(res => {
    ElMessage.success(res.data || '订单合并成功')
    mergeOrderDialogVisible.value = false
    initData() // 刷新订单列表
  }).catch(err => {
    ElMessage.error(err.response?.data?.message || '订单合并失败')
    console.error(err)
  })
}


onMounted(()=>{
  initData()
  getOrderSource()
  getOrderStatus()
  fetchStatusCounts()
})
</script>

<template>
  <div class="order-management">
    <div class="header">
      <h2>订单管理</h2>
    </div>

    <!-- 订单状态卡片 -->
    <div class="status-cards">
      <el-card
          shadow="hover"
          class="status-card"
          @click="handleStatusClick('full')"
      >
        <div class="card-title">全部</div>
        <div class="card-value">{{ statusCounts['全部']  }}</div>
      </el-card>
      <el-card
          shadow="hover"
          class="status-card"
          @click="handleStatusClick('1')"
      >
        <div class="card-title">待付款</div>
        <div class="card-value">{{ statusCounts['待付款'] }}</div>
      </el-card>
      <el-card
          shadow="hover"
          class="status-card"
          @click="handleStatusClick('2')"
      >
        <div class="card-title">待发货</div>
        <div class="card-value">{{ statusCounts['待发货'] }}</div>
      </el-card>
      <el-card
          shadow="hover"
          class="status-card"
          @click="handleStatusClick('3')"
      >
        <div class="card-title">已发货</div>
        <div class="card-value">{{ statusCounts['已发货'] }}</div>
      </el-card>
      <el-card
          shadow="hover"
          class="status-card"
          @click="handleStatusClick('4')"
      >
        <div class="card-title">已完成</div>
        <div class="card-value">{{ statusCounts['已完成'] }}</div>
      </el-card>
      <el-card
          shadow="hover"
          class="status-card"
          @click="handleStatusClick('5')"
      >
        <div class="card-title">已关闭</div>
        <div class="card-value">{{ statusCounts['已关闭'] }}</div>
      </el-card>
    </div>

    <!-- 查询条件 -->
    <el-card shadow="never" class="query-card">
      <div class="query-header">
        <div class="query-title">操作</div>
        <el-button
            type="text"
            @click="showAdvancedDialog = true"
            class="toggle-advanced-btn"
        >
          高级筛选
          <el-icon><Search /></el-icon>
        </el-button>
      </div>

      <el-form :inline="true" :model="queryForm" class="query-form">
        <el-form-item label="编号：" class="query-form-item">
          <el-input
              v-model="queryForm.orderNumber"
              placeholder="请输入订单编号"
              clearable
              class="query-input"
          />
        </el-form-item>
        <el-form-item label="用户账号：" class="query-form-item">
          <el-input
              v-model="queryForm.userAccount"
              placeholder="请输入用户账号"
              clearable
              class="query-input"
          />
        </el-form-item>
        <el-form-item label="订单状态：" class="query-form-item">
          <el-select
              v-model="queryForm.orderStatus"
              placeholder="全部"
              clearable
              class="query-select"
          >
            <el-option
                v-for="item in statusOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
            <el-option label="全部" :value="''" />
          </el-select>
        </el-form-item>
        <el-form-item class="query-form-item">
          <el-button type="info" @click="resetQuery" class="action-btn">重置</el-button>
          <el-button type="primary" @click="handleQuery" class="action-btn">查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 高级筛选弹窗 -->
      <el-dialog
          v-model="showAdvancedDialog"
          title="高级筛选"
          width="600px"
          :close-on-click-modal="false"
      >
        <el-form :model="advancedForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="订单编号">
                <el-input v-model="advancedForm.orderNumber" placeholder="请输入订单编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户账号">
                <el-input v-model="advancedForm.userAccount" placeholder="请输入用户账号" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="订单状态">
                <el-select
                    v-model="advancedForm.orderStatus"
                    placeholder="全部"
                    clearable
                >
                  <el-option
                      v-for="item in statusOption"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单来源">
                <el-select v-model="advancedForm.orderSource" placeholder="全部" clearable>
                  <el-option
                      v-for="(item, index) in sourceOption"
                      :key="index"
                      :label="item"
                      :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <<el-form-item label="下单日期">
          <el-date-picker
              v-model="advancedForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%"
              @change="handleDateChange"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="resetAdvancedForm">重置</el-button>
            <el-button type="primary" @click="applyAdvancedFilter">查询</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="openMergeOrderDialog">合并订单</el-button>
      <el-button @click="printPreview">打印预览单</el-button>
      <el-button @click="exportOrder">导出订单</el-button>
    </div>

    <el-dialog
        v-model="mergeOrderDialogVisible"
        title="合并订单"
        width="600px"
        class="merge-order-dialog"
    >
      <el-form label-width="100px">
        <el-form-item label="主订单" required>
          <el-select
              v-model="mainOrder"
              placeholder="请选择主订单"
              clearable
              style="width: 100%"
              @change="subOrders = []"
          >
            <el-option
                v-for="order in mergeOrderOptions"
                :key="order.id"
                :label="`${order.orderNumber} (${order.userAccount}) - ¥${order.orderAmount}`"
                :value="order.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="从订单" required>
          <el-select
              v-model="subOrders"
              placeholder="请选择从订单"
              multiple
              style="width: 100%"
              :disabled="!mainOrder"
          >
            <el-option
                v-for="order in mergeOrderOptions.filter(o => o.id !== mainOrder)"
                :key="order.id"
                :label="`${order.orderNumber} (${order.userAccount}) - ¥${order.orderAmount}`"
                :value="order.id"
            />
          </el-select>
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button @click="mergeOrderDialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="confirmMergeOrder"
            :disabled="!mainOrder || subOrders.length === 0"
        >
          确认合并
        </el-button>
      </template>
    </el-dialog>

    <!-- 订单表格 -->
    <el-card shadow="never">
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column
            type="selection"
            width="55"
            align="center"
        />
        <el-table-column prop="orderNumber" label="订单编号" width="180" />
        <el-table-column prop="productName" label="订单商品" />
        <el-table-column prop="orderAmount" label="订单金额" width="120" />
        <el-table-column prop="orderTime" label="下单时间" width="160" />
        <el-table-column prop="userAccount" label="用户账号" width="130" />
        <el-table-column prop="orderSource" label="订单来源" width="120" />
        <el-table-column prop="paymentMethod" label="支付方式" width="120" />
        <el-table-column prop="orderStatus" label="订单状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.orderStatus)">
              {{ typeof row.orderStatus === 'number' ? statusMap[row.orderStatus] : row.orderStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="viewOrder(row)">查看订单</el-button>
            <el-button
                type="text"
                size="small"
                @click="closeOrder(row)"
            >
              关闭订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
          v-model="closeOrderDialogVisible"
          title="关闭订单"
          width="500px"
      >
        <el-form :model="advancedForm" label-width="100px">
          <el-form-item label="操作描述" prop="description">
            <el-input
                v-model="operationDescription"
                type="textarea"
                :rows="4"
                placeholder="请输入关闭订单的原因"
            />
          </el-form-item>
        </el-form>

        <template #footer>
    <span class="dialog-footer">
      <el-button @click="closeOrderDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmCloseOrder">确定</el-button>
    </span>
        </template>
      </el-dialog>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.order-management {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: bold;
}

.status-cards {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.status-card {
  flex: 1;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.status-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
}

.card-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.query-card {
  margin-bottom: 20px;
}

.query-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #333;
}

.query-form {
  margin-bottom: 0;
}

.advanced-filter {
  margin-top: 16px;
  padding: 16px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.action-buttons {
  margin-bottom: 16px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 16px;
}
   /* 查询卡片 */
 .query-card {
   margin-bottom: 20px;
   border-radius: 4px;
   border: 1px solid #ebeef5;
 }

/* 查询头部 */
.query-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.query-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.toggle-advanced-btn {
  padding: 0;
  color: #409eff;
  font-size: 13px;
}

.toggle-icon {
  margin-left: 4px;
  transition: transform 0.3s;
}

.toggle-icon.is-active {
  transform: rotate(180deg);
}

/* 查询表单 */
.query-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px 12px;
  margin-bottom: 0;
}

.query-form-item {
  margin: 0;
  display: flex;
  align-items: center;
}

.query-form-item :deep(.el-form-item__label) {
  padding-right: 8px;
  font-size: 13px;
  color: #606266;
  line-height: 32px;
}

.query-input, .query-select {
  width: 180px;
}

.query-input :deep(.el-input__wrapper),
.query-select :deep(.el-input__wrapper) {
  height: 32px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.query-input :deep(.el-input__inner),
.query-select :deep(.el-input__inner) {
  height: 30px;
  line-height: 30px;
}

.action-btn {
  height: 32px;
  padding: 7px 15px;
  font-size: 13px;
}

/* 高级筛选 */
.advanced-filter {
  margin-top: 12px;
  padding: 16px;
  background-color: #f8fafc;
  border-radius: 4px;
  border: 1px dashed #e4e7ed;
}

.advanced-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px 12px;
}

.advanced-form-item {
  margin: 0;
  display: flex;
  align-items: center;
}

.advanced-form-item :deep(.el-form-item__label) {
  padding-right: 8px;
  font-size: 13px;
  color: #606266;
  line-height: 32px;
}

.date-picker {
  width: 240px;
}

.advanced-select {
  width: 160px;
}

.date-picker :deep(.el-input__wrapper),
.advanced-select :deep(.el-input__wrapper) {
  height: 32px;
}

.date-picker :deep(.el-input__inner),
.advanced-select :deep(.el-input__inner) {
  height: 30px;
  line-height: 30px;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .query-input, .query-select {
    width: 160px;
  }

  .date-picker {
    width: 220px;
  }

  .advanced-select {
    width: 140px;
  }
}

@media (max-width: 768px) {
  .query-form, .advanced-form {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .query-form-item, .advanced-form-item {
    width: 100%;
  }

  .query-input, .query-select,
  .date-picker, .advanced-select {
    width: 100% !important;
  }

  .action-btn {
    margin-top: 8px;
  }
}

:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  margin-right: 0;
}

:deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  color: #606266;
  font-weight: normal;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 20px;
  border-top: 1px solid #ebeef5;
}

.dialog-footer .el-button {
  padding: 8px 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
    max-width: 400px;
  }

  :deep(.el-col) {
    width: 100% !important;
  }
}
.status-card {
  cursor: pointer;
  transition: all 0.3s;
}

.status-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
}

.action-buttons {
  margin-bottom: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>